package com.hsgene.user.controller.customer;

import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.user.condition.ShoppingMallCustomerCondition;
import com.hsgene.user.converter.UserConverter;
import com.hsgene.user.dto.user.customer.CustomerDto;
import com.hsgene.user.service.CustomerService;
import com.hsgene.user.session.UserSessionComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 客户信息Controller
 *
 * @author wangbing
 * @version 1.0, 2018/7/6
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Resource
    private UserSessionComponent userSessionComponent;

    /**
     * 获取用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    /*@GetMapping("{userId}")
    public ApiResult<CustomerDto> getUserInfo(
            @PathVariable("userId") String userId) {
        return customerService.findCustomerById(userId);
    }*/

    /**
     * 更新用户信息
     *
     * @param customer 用户信息
     * @return 更新结果
     */
    @PutMapping("")
    public ApiResult<NullObject> updateCustomer(@RequestBody CustomerDto customer) {
        ApiResult<NullObject> result = customerService.updateCustomer(customer);
        if (result.isSucc()) {
            // 用户信息更新成功，更新UserSession缓存的用户信息
            UserInfo userInfo = UserConverter.buildUserInfo(customer, null);
            userInfo.setSessionId(customer.getUserSession().getSessionId());
            userSessionComponent.refreshUserInfo(userInfo);
        }
        return result;
    }

    /**
     * 用户管理列表
     * @param condition 查询条件
     * @param page 页码
     * @param size 大小
     * @return
     */
    @GetMapping
    public ApiResult customers(ShoppingMallCustomerCondition condition,Integer page,Integer size){
        try {
            if(page==null||size==null){
                return new ApiResult(5001,"failed","分页条件不能为空",null);
            }
            LimitHelper limitHelper = LimitHelper.create(page, size, true);
            condition.setLimitHelper(limitHelper);
            return customerService.customers(condition);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(500,"failed","数据获取出错",e.toString());
        }
    }

}
